package com.vercon.moensmart.utils

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.FragmentActivity
import com.vercon.common.utils.LogUtils
import com.vercon.common.utils.TopActivityManager
import com.vercon.moensmart.MainActivity
import java.util.concurrent.CopyOnWriteArrayList

class ForegroundCallbacks : Application.ActivityLifecycleCallbacks {
    interface Listener {
        fun onBecameForeground()
        fun onBecameBackground()
        fun onActivityCreated(activity: Activity?)
        fun onActivityResumed(activity: Activity?)
    }

    var isForeground = false
        private set
    private var paused = true
    private val handler = Handler()
    private val listeners: MutableList<Listener> = CopyOnWriteArrayList()
    private var mRunnable: Runnable? = null
    val isBackground: Boolean
        get() = !isForeground

    fun addListener(listener: Listener) {
        listeners.add(listener)
    }

    fun removeListener(listener: Listener) {
        listeners.remove(listener)
    }

    override fun onActivityResumed(activity: Activity) {
        if (activity is FragmentActivity) {
            TopActivityManager.getInstance().currentActivity = activity
            paused = false
            val wasBackground = !isForeground
            isForeground = true
            for (l in listeners) {
                try {
                    l.onActivityResumed(activity)
                } catch (exc: Exception) {
                    LogUtils.d("Listener threw exception!:$exc")
                }
            }
            if (mRunnable != null) handler.removeCallbacks(mRunnable!!)
            if (wasBackground) {
                LogUtils.d("went foreground")
                for (l in listeners) {
                    try {
                        l.onBecameForeground()
                    } catch (exc: Exception) {
                        LogUtils.d("Listener threw exception!:$exc")
                    }
                }
            } else {
                LogUtils.d("still foreground")
            }
        }
    }

    override fun onActivityPaused(activity: Activity) {}
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        if (activity is FragmentActivity) {
            TopActivityManager.getInstance().currentActivity = activity
            for (l in listeners) {
                try {
                    l.onActivityCreated(activity)
                } catch (exc: Exception) {
                    LogUtils.d("Listener threw exception!:$exc")
                }
            }
        }
    }

    override fun onActivityStarted(activity: Activity) {}
    override fun onActivityStopped(activity: Activity) {
        if (activity is com.vercon.moensmart.MainActivity && !isRunning(activity)) {
            paused = true
            if (mRunnable != null) handler.removeCallbacks(mRunnable!!)
            handler.postDelayed(Runnable {
                if (isForeground && paused) {
                    isForeground = false
                    LogUtils.d("went background")
                    for (l in listeners) {
                        try {
                            l.onBecameBackground()
                        } catch (exc: Exception) {
                            LogUtils.d("Listener threw exception!:$exc")
                        }
                    }
                } else {
                    LogUtils.d("still foreground")
                }
            }.also { mRunnable = it }, CHECK_DELAY)
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
    override fun onActivityDestroyed(activity: Activity) {}
    fun isRunning(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        //获得当前运行的task(任务)
        val taskInfoList = activityManager.getRunningTasks(10)
        return if (taskInfoList != null && taskInfoList.size > 0) {
            taskInfoList[0].topActivity!!.packageName == context.packageName
        } else false
    }

    companion object {
        const val CHECK_DELAY: Long = 1000 //暂停时延迟1000毫秒回调
        val TAG = ForegroundCallbacks::class.java.name
        private var instance: ForegroundCallbacks? = null
        fun init(application: Application): ForegroundCallbacks? {
            if (instance == null) {
                instance = ForegroundCallbacks()
                application.registerActivityLifecycleCallbacks(instance)
            }
            return instance
        }

        operator fun get(application: Application): ForegroundCallbacks? {
            if (instance == null) {
                init(application)
            }
            return instance
        }

        operator fun get(ctx: Context): ForegroundCallbacks? {
            if (instance == null) {
                val appCtx = ctx.applicationContext
                if (appCtx is Application) {
                    init(appCtx)
                }
                throw IllegalStateException(
                    "Foreground is not initialised and " +
                            "cannot obtain the Application object"
                )
            }
            return instance
        }

        fun get(): ForegroundCallbacks? {
            checkNotNull(instance) {
                "Foreground is not initialised - invoke " +
                        "at least once with parameterised init/get"
            }
            return instance
        }
    }
}